import { getCurrentSheetIndex } from "../global/api";
import method from "../global/method";
import { getSheetIndex } from "../methods/get";
import Store from "../store";

const checkCellEditPermission = (r_index, c_index, data, sheetIndex = getCurrentSheetIndex()) => {
    const file = Store.luckysheetfile[sheetIndex];
    if (file.edit === false) return false;
    if (!data[r_index] || !data[r_index][c_index]) return true;
    const edit = !(data[r_index][c_index].edit === false);
    return edit;
};

const checkRangeEditPermission = (rangeList, sheetIndex) => {
    const index = getSheetIndex(sheetIndex || Store.currentSheetIndex);
    const file = Store.luckysheetfile[index];
    if (file.edit === false) return false;
    const data = file.data;
    for (let i = 0; i < rangeList.length; i++) {
        const { row, column } = rangeList[i];
        let r1 = row[0], r2 = row[1];
        let c1 = column[0], c2 = column[1];
        for (let r = r1; r <= r2; r++) {
            for (let c = c1; c <= c2; c++) {
                const cell = data[r] ? data[r][c] || {} : {};
                if (cell.edit === false) return false;
            }
        }
    }
    return true;
};

const noFreeze = (r, c, sheetIndex) => {
    let curIndex = method.getInputSheetIndex(sheetIndex);
    const file = Store.luckysheetfile[curIndex];
    if (!file.frozen) return true;
    let row_focus, column_focus;
    switch (file.frozen.type) {
    case 'row':
        return r !== 0;
    case 'column':
        return c !== 0;
    case 'both':
        return r !== 0 && c !== 0;
    case 'rangeRow':
        row_focus = file.frozen.range.row_focus;
        return r > row_focus;
    case 'rangeColumn':
        column_focus = file.frozen.range.column_focus;
        return c > column_focus;
    case 'rangeBoth':
        row_focus = file.frozen.range.row_focus;
        column_focus = file.frozen.range.column_focus;
        return r > row_focus && c > column_focus;
    case 'cancel':
        return true;
    default:
        return true;
    }
};

export {
    checkCellEditPermission,
    checkRangeEditPermission,
    noFreeze
};
